package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.AbstractDocument.BranchElement;

import oracle.net.aso.n;
import dao.UserDao;
import dao.impl.UserDaoImpl;
import pojo.User;
import util.CheckoutBirth;

/**
 * Servlet implementation class SubmitServlet
 */
public class SubmitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SubmitServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//接收的request采用utf-8编码
		request.setCharacterEncoding("UTF-8");
		//获取到请求表单的参数
		String name = request.getParameter("uname");
		String sal = request.getParameter("sal");
		String birth = request.getParameter("birth");
		String sex = request.getParameter("male");
		
		System.out.println(name+sal+birth+sex);
		
		User user = new User();
		user.setName(name);
		user.setSal(Double.parseDouble(sal));
		//校验生日格式
		Date birthDate = CheckoutBirth.CheckedBirth(birth);
		
		if(birthDate==null){
			//生日格式有误则重定向到错误页面
			response.sendRedirect("error");
		}else{
			user.setBirth(birthDate);
			if(sex == null){
				user.setSex(false);
			}else {
				user.setSex(true);
			}
			UserDao userDao = new UserDaoImpl();
			int m=userDao.addUser(user);
			if(m==0){
				response.sendRedirect("error");
			}else{
				String info = "提交成功!!!";
				response.setContentType("text/html;charset=UTF-8");
				PrintWriter writer = response.getWriter();
				writer.write(info);
				writer.close();
			}
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("get...");
	}

}
